/*
 *  Copyright 2015-2016, RenGu Technology (BeiJing) Co., Ltd.
 *  All right reserved.
 *
 *  THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF RENGU TECHNOLOGY (BeiJing) CO., LTD.
 *
 *  THE CONTENTS OF THIS FILE MAY NOT BE DISCLOSED TO THIR PARTIES,
 *  COPIED OR DUPLICATED IN ANY FORM, IN WHOLE OR IN PART,
 *  WITHOUT THE PRIOR WRITTEN PERMISSION OF RENGU TECHNOLOGY (BeiJing) CO., LTD.
 *
 *  NcqsPaymentServiceImpl
 *
 *  Edit History:
 *      wukefan Created on 2020年08月19日
 *
 */
package cc.rengu.igas.route.core.realize.payment.impl.ncqs;

import cc.rengu.igas.channel.ncqs.biz.impl.NcqsPayServiceImpl;
import cc.rengu.igas.channel.ncqs.facade.base.Header;
import cc.rengu.igas.channel.ncqs.facade.request.NcqsAgreePayAcqRequest;
import cc.rengu.igas.channel.ncqs.facade.response.NcqsAgreePayAcqResponse;
import cc.rengu.igas.channel.ncqs.facade.result.Result;
import cc.rengu.igas.route.common.constant.SmartRouteParamConstant;
import cc.rengu.igas.route.common.enums.SmartRouteRspEnums;
import cc.rengu.igas.route.core.realize.payment.DstChannelPaymentService;
import cc.rengu.igas.route.facade.request.IntelligencePaymentRequest;
import cc.rengu.igas.route.facade.request.IntelligencePaymentVerifyRequest;
import cc.rengu.igas.route.facade.request.IntelligenceResultQueryRequest;
import cc.rengu.igas.route.facade.response.IntelligencePaymentResponse;
import cc.rengu.igas.route.facade.response.IntelligencePaymentVerifyResponse;
import cc.rengu.igas.route.facade.response.IntelligenceResultQueryResponse;
import cc.rengu.igas.share.common.constant.ShareParamConstant;
import cc.rengu.oltp.service.common.dao.SignAcctInfoMapper;
import cc.rengu.oltp.service.common.dao.impl.SignAcctInfoMapperImpl;
import cc.rengu.oltp.service.common.entity.SignAcctInfo;
import cc.rengu.oltp.service.common.entity.SysParam;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.SysParamService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.service.realize.impl.SysParamServiceImpl;
import cc.rengu.oltp.utility.util.BeanUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.List;

/**
 * 无卡快捷协议支付实现
 *
 * @author lizhangtao
 * @version 1.0
 * @date 2020/8/19
 */
public class NcqsPaymentServiceImpl implements DstChannelPaymentService {

    private RgLogger rglog = RgLog.getLogger(this.getClass().getSimpleName());

    @Override
    public IntelligencePaymentResponse payment(IntelligencePaymentRequest intelligencePaymentRequest) throws Exception {
        IntelligencePaymentResponse intelligencePaymentResponse = new IntelligencePaymentResponse();
        intelligencePaymentResponse.setHeader(intelligencePaymentRequest.getHeader());
        intelligencePaymentResponse.setDstChannelTxnNum("1001");
        intelligencePaymentResponse.setDstChannelId("NCQS");
        NcqsAgreePayAcqRequest ncqsAgreePayAcqRequest = new NcqsAgreePayAcqRequest();
//        ncqsAgreePayAcqRequest.setOrderDesc();
//        ncqsAgreePayAcqRequest.setTermType();
//        ncqsAgreePayAcqRequest.setAcctInType();
        ncqsAgreePayAcqRequest.setBusiFuncType("111011");
        ncqsAgreePayAcqRequest.setBusiType("100003");
        SysParamService sysParamService = new SysParamServiceImpl();
        SysParam sysParam = sysParamService.getSysParamInfo(intelligencePaymentRequest.getHeader().getInstId(), SmartRouteParamConstant.OPMS_SYS_PARAM, SmartRouteParamConstant.NCQS_INST_CODE);
        if (null == sysParam || StringUtil.isEmptyOrNull(sysParam.getParamValue())) {
            rglog.error("未获取到<{}>机构转换为银联无卡快捷数据或者机构转换数据不存在", intelligencePaymentRequest.getHeader().getInstId());
            throw new BizException(SmartRouteRspEnums.CONFIG_ERROR.getRespCode(), SmartRouteRspEnums.CONFIG_ERROR.getRespDesc());
        }
        ncqsAgreePayAcqRequest.setCupsInstCode(sysParam.getParamValue());
        ncqsAgreePayAcqRequest.setPayeeAcctIssrId(sysParam.getParamValue());
        //商户号补充到15位
        if (intelligencePaymentRequest.getMchntNo().length() < 15) {
            ncqsAgreePayAcqRequest.setCupsMchntNo(intelligencePaymentRequest.getMchntNo() + String.format("%0" + (15 - intelligencePaymentRequest.getMchntNo().length()) + "d", 0));
        } else if (intelligencePaymentRequest.getMchntNo().length() > 15) {
            ncqsAgreePayAcqRequest.setCupsMchntNo(intelligencePaymentRequest.getMchntNo().substring(intelligencePaymentRequest.getMchntNo().length() - 15));
        } else {
            ncqsAgreePayAcqRequest.setCupsMchntNo(intelligencePaymentRequest.getMchntNo());
        }
        ncqsAgreePayAcqRequest.setMchntName(intelligencePaymentRequest.getMchntName());
        ncqsAgreePayAcqRequest.setOrderAmt(intelligencePaymentRequest.getTxnAmt());
        ncqsAgreePayAcqRequest.setOrderCcy(intelligencePaymentRequest.getTxnCrcyCode());
        ncqsAgreePayAcqRequest.setOrderId(intelligencePaymentRequest.getHeader().getTraceNo());
        ncqsAgreePayAcqRequest.setPayAcctNo(intelligencePaymentRequest.getPayerInfo().getAcctNo());
        String acctNo = intelligencePaymentRequest.getPayerInfo().getAcctNo();
        String sgnNo = intelligencePaymentRequest.getPayerInfo().getSgnNo();
        if (StringUtil.isEmptyOrNull(sgnNo) && StringUtil.isEmptyOrNull(acctNo)) {
            rglog.error("协议号与账号必送其一");
            throw new BizException(SmartRouteRspEnums.MSG_VALID_CHECK_ERROR.getRespCode(), SmartRouteRspEnums.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
        if (StringUtil.isEmptyOrNull(sgnNo)) {
            SignAcctInfoMapper signAcctInfoMapper = new SignAcctInfoMapperImpl();
            List<SignAcctInfo> signAcctInfoList = signAcctInfoMapper.selectSignAcctInfoBySignAcctNo(intelligencePaymentRequest.getHeader().getInstId(), acctNo);
            if (null == signAcctInfoList || signAcctInfoList.isEmpty()) {
                rglog.error("未查询到签约信息");
                throw new BizException(SmartRouteRspEnums.TRANS_FAIL.getRespCode(), SmartRouteRspEnums.TRANS_FAIL.getRespDesc());
            }
            signAcctInfoList.stream().filter(item -> "03".equals(item.getSignAcctType()) && "00".equals(item.getSignType()) && "Y".equals(item.getSignStatus())).findFirst();
            if (signAcctInfoList.isEmpty()) {
                rglog.error("未查询到签约信息");
                throw new BizException(SmartRouteRspEnums.TRANS_FAIL.getRespCode(), SmartRouteRspEnums.TRANS_FAIL.getRespDesc());
            }
            String signToken = signAcctInfoList.get(0).getSignToken();
            String[] array = signToken.split("\\|");
            if (2 != array.length) {
                rglog.error("签约协议号记录错误");
                throw new BizException(SmartRouteRspEnums.TRANS_FAIL.getRespCode(), SmartRouteRspEnums.TRANS_FAIL.getRespDesc());
            }
            ncqsAgreePayAcqRequest.setSignNo(array[1]);
        }
        ncqsAgreePayAcqRequest.setMchntType("4816");
        ncqsAgreePayAcqRequest.setNcqsReserve(intelligencePaymentRequest.getAdditionInfo());
        Header header = new Header();
        BeanUtil.beanCopy(intelligencePaymentRequest.getHeader(), header);
        header.setTxnNum("1001");
        if (!StringUtil.isEmptyOrNull(intelligencePaymentRequest.getAdditionInfo())) {
            JSONObject jsonObject = JSON.parseObject(intelligencePaymentRequest.getAdditionInfo());
            if (null != jsonObject) {
                String esbSequenceNumber = jsonObject.getString(ShareParamConstant.ESB_SEQUENCE_NUMBER);
                if (!StringUtil.isEmptyOrNull(esbSequenceNumber)) {
                    header.setTraceNo(esbSequenceNumber);
                }
            }
        }
        if (StringUtil.isEmptyOrNull(header.getTraceNo())) {
            rglog.error("无esb流水号，交易失败");
            throw new BizException(SmartRouteRspEnums.TRANS_FAIL.getRespCode(), SmartRouteRspEnums.TRANS_FAIL.getRespDesc());
        }
        ncqsAgreePayAcqRequest.setHeader(header);
        ncqsAgreePayAcqRequest.setTermType("07");
        DubboService dubboService = new DubboServiceImpl();
        Result<NcqsAgreePayAcqResponse> agreePay = (Result<NcqsAgreePayAcqResponse>)
                dubboService.callDubboInnerMethod(NcqsPayServiceImpl.class, "agreePay", ncqsAgreePayAcqRequest);
        if (!agreePay.isSuccess() || null == agreePay.getResult()) {
            rglog.error("交易未应答信息");
            throw new BizException(SmartRouteRspEnums.TRANS_TO.getRespCode(), SmartRouteRspEnums.TRANS_TO.getRespDesc());
        }
        intelligencePaymentResponse.setRespCode(agreePay.getResult().getRespCode());
        intelligencePaymentResponse.setRespDesc(agreePay.getResult().getRespDesc());
        if (OltpRpcdEnum.TRANS_SUCCESS.getRespCode().equals(agreePay.getResult().getRespCode())) {
            intelligencePaymentResponse.setDstChannelSsn(agreePay.getResult().getSettleKey());
            intelligencePaymentResponse.setSettleDate(agreePay.getResult().getSettleDate());
        }
        return intelligencePaymentResponse;
    }

    @Override
    public IntelligencePaymentVerifyResponse paymentVerify(IntelligencePaymentVerifyRequest intelligencePaymentVerifyRequest) throws Exception {
        //无卡快捷的协议支付不需要确认
        throw new BizException(SmartRouteRspEnums.NO_AUTH_ERROR.getRespCode(), SmartRouteRspEnums.NO_AUTH_ERROR.getRespDesc());
    }

    @Override
    public IntelligenceResultQueryResponse query(IntelligenceResultQueryRequest resultQueryRequest) throws Exception {
        return null;
    }

    @Override
    public String getReconKey(IntelligencePaymentRequest intelligencePaymentRequest) throws Exception {
        //无卡快捷间连，通过esb，对账key为
        String esbSequenceNumber = null;
        if (!StringUtil.isEmptyOrNull(intelligencePaymentRequest.getAdditionInfo())) {
            JSONObject jsonObject = JSON.parseObject(intelligencePaymentRequest.getAdditionInfo());
            if (null != jsonObject) {
                esbSequenceNumber = jsonObject.getString(ShareParamConstant.ESB_SEQUENCE_NUMBER);
            }
        }
        if (!StringUtil.isEmptyOrNull(esbSequenceNumber)) {
            return esbSequenceNumber;
        } else {
            rglog.error("无esb流水号，交易失败");
            throw new BizException(SmartRouteRspEnums.TRANS_FAIL.getRespCode(), SmartRouteRspEnums.TRANS_FAIL.getRespDesc());
        }
    }
}
